'use strict';

// const proxyUrl = 'http://127.0.0.1:1080/'
const Controller = require('egg').Controller;
const googleTrends = require('google-trends-api');
// const HttpsProxyAgent = require('https-proxy-agent');
const dd = console.log
const dayjs = require('dayjs')
// const proxyAgent = new HttpsProxyAgent(proxyUrl);
const fs = require('fs')
const cache = ['BALENCIAGA', 'CELINE', 'CHLOE', 'DIOR', 'GIVENCHY', 'GUCCI', 'HERMES', 'LOUIS VUITTION', 'PRADA', 'YSL']

async function getOverTime(params) {
  return await googleTrends.interestOverTime(params);
}

async function getByRegion(params) {
  return await googleTrends.interestByRegion(params)
}

async function getRelatedQuery(params) {
  return await googleTrends.relatedQueries(params)
}

async function getRelatedTopic(params) {}

function read(dir) {
  return new Promise((resolve, reject) => {
    fs.readFile(dir, 'utf-8', (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

function getTimeRange(time) {
  switch (time) {
    case 3:
      return [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    case 4:
      return [dayjs().subtract(90, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    case 5:
      return [dayjs().subtract(180, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    case 6:
      return [dayjs().subtract(1, 'year').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  }
}


class HomeController extends Controller {
  async index() {
    const ctx = this.ctx;
    const rb = ctx.request.body;
    const keyword = rb.keywords.map(item => {
      return item.toUpperCase()
    })
    const time = +rb.time;
    const [startTime, endTime] = getTimeRange(time)
    const params = {
      keyword: rb.keywords,
      // agent: proxyAgent,
      geo: "",
      startTime: new Date(startTime),
      endTime: new Date(endTime),
      category: 0,
      property: ""
    };
    const query = {
      // agent: proxyAgent,
      keyword: rb.keywords
    }
    const relatedQ = [];
    for (let i = 0; i < keyword.length; i++) {
      let data;
      const query = './cache/' + keyword[i] + '.json'
      if (cache.includes(keyword[i])) {
        data = await read(query)
      } else {
        data = await getRelatedQuery({
          // agent: proxyAgent,
          keyword: keyword[i]
        })
      }
      data = JSON.parse(data)
      data = data.default.rankedList[1]
      relatedQ.push(data)
    }
    const results = await Promise.all([getOverTime(params), getByRegion(params)]);
    ctx.body = {
      lineData: JSON.parse(results[0]),
      mapData: JSON.parse(results[1]),
      relatedQ: relatedQ,
    };
  }
}

module.exports = HomeController;